package com.example.crmdemo.Crm.service.Impl;

import com.example.crmdemo.Crm.mapper.UserMapper;
import com.example.crmdemo.Crm.entity.User;
import com.example.crmdemo.security.EncryptionService;
import com.example.crmdemo.security.JwtTokenProvider;
import com.example.crmdemo.Crm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private EncryptionService encryptionService;
    @Autowired
    private JwtTokenProvider jwtTokenProvider;

    @Override
    public String login(String username, String password) {
        User user = userMapper.findByUsername(username);
        if (user != null && encryptionService.decrypt(user.getPassword()).equals(password)) {
            return jwtTokenProvider.createToken(username, user.getRole());
        }
        throw new IllegalArgumentException("Invalid username or password supplied");
    }

    @Override
    public void register(User user) {
        user.setPassword(encryptionService.encrypt(user.getPassword()));
        user.setRole("user"); // 默认角色为user
        userMapper.insert(user);
    }

    @Override
    public void updatePassword(String username, String newPassword) {
        User user = userMapper.findByUsername(username);
        if (user != null) {
            user.setPassword(encryptionService.encrypt(newPassword));
            userMapper.updateById(user);
        } else {
            throw new IllegalArgumentException("User not found");
        }
    }

    @Override
    public void deleteUser(String username) {
        userMapper.deleteById(username);
    }

    @Override
    public void updateUser(User user) {
        User existingUser = userMapper.findByUsername(user.getUsername());
        if (existingUser != null) {
            userMapper.updateById(user);
        } else {
            throw new IllegalArgumentException("User not found");
        }
    }

    @Override
    public User getUserByUsername(String username) {
        return userMapper.findByUsername(username);
    }

    @Override
    public List<User> getAllManagers() {
        return userMapper.getAllManagers();
    }

    @Override
    public List<User> getAllUsers() {
        return userMapper.getAllUsers();
    }

    @Override
    public List<User> searchUsers(String username) {
        return userMapper.getUserByUsername(username);
    }
}
